<?php
/* 名称：商品管理控制器
 * 创建：nrf
 * 修改：
 *
 */
 
namespace Admin\Controller;
use Think\Controller;
use Think\page;

class GoodsManageController extends BaseController {

	function _initialize() {
		parent::_initialize ();
	}

	
	//商品多属性查看
	public function goodsAttrs(){
		 
		$list_rows = 15;//C('LIST_ROWS');//每页条数
		 
		$db = M('goods_attribute_category');
		 
		$total=$db->alias('b')->where($where)->count();   //获取总页数
		$page = new \Think\Page($total,$list_rows);
		$options = $page->firstRow.','.$page->listRows;
		
		$list = $db->order('sort desc')->limit($options)->select();
		$this->assign('_list',  $list);
		$totalPages = ceil($total/$list_rows);
		$this->assign('categoryTotalpages',$totalPages);
		
		$this->display();
	}
	
	/* 商品属性分类分页 */
	public function loadAttrCategoryData(){
		$curPage = I('request.curPage',1,'intval');
    	 
    	$limitStr = (($curPage-1)*15).',15';
		
    	$db = M('goods_attribute_category');
		$list = $db->order('sort desc')->limit($limitStr)->select();
		$this->assign('_list',  $list);
		
		$this->display();
	}
	
    /* 加载属性组列表数据 */
    public function loadAttrGroupData(){
    	 $cat_id = I('request.cat_id',0,'intval');
    	 
    	 $curPage = I('request.curPage',1,'intval');
    	 
    	 $limitStr = (($curPage-1)*12).',12';
    	 
    	 $groups = M('goods_attribute_group')->order('sort desc')->where(array('cat_id'=>$cat_id,'is_delete'=>0))->limit($limitStr)->select();
    	 $this->assign('groups',$groups);
    	 
    	 $_count =  M('goods_attribute_group')->order('sort desc')->where(array('cat_id'=>$cat_id,'is_delete'=>0))->count();
    	 $totalPage = ceil($_count/12);
		 $this->assign('totalPage',$totalPage);
    	 
    	 $this->display();    	 
    }
    /* 加载属性值列表数据 */
    public function loadAttrGroupValData(){
    	$group_id = I('request.group_id',0,'intval');
    	
    	$where = array('attribute_group_id'=>$group_id);
    	
    	//,'is_delete'=>0
    	
    	$p=I('request.p',1,'intval');
    	$this->assign('cur_page',$p);//当前页数
    	$this->list_rows = 12;//每页条数
    	 
    	$db = M('goods_attribute_value');
    	 
    	$total=$db->alias('b')->where($where)->count();   //获取总页数
    	$page = new \Think\Page($total,12);
    	$page->setConfig("prev", "上一页");
    	$page->setConfig("next", "下一页");
    	$page->parameter['group_id'] = $group_id;
    	$options = $page->firstRow.','.$page->listRows;
    	
    	$groupVals = $db->where($where)->order('sort desc')->limit($options)->select();
//     	echo $db->getLastSql();
    	$this->assign('groupVals',  $groupVals);
    	$this->assign('_page', $page->show());
    	
    	
    	$this->display();
    }
    
    //商品列表页
    public function index(){

    	$is_warn_number=I("request.is_warn_number");
    	$this->assign("is_warn_number",$is_warn_number);
   
    	//查询商品类别
    	$cat_list=M('category')->where(array('isshow'=>1))->order('sort_order')->select();
    	$goods_cats = list_to_tree($cat_list,'cat_id','parent_id','childs');
    	$this->assign('categorylist',$goods_cats);
    	
    	//查询商品品牌
    	$brand_list=M('brand')->where(array('isshow'=>1))->order('sort_order')->select();
    	$this->assign('brandlist',$brand_list);
    
    	$this->goods_cg_count=M("goods")->where(array('status'=>0,'is_delete'=>0))->count();
    
    	$this->assign("page_title","商品列表");
    	$this->display();
    
    }
    //商品异步加载
    public  function index_list(){
    
    	$keywords = I('request.keywords','','trim');
    	if( !empty($keywords) ){
    		$where['goods_sn|goods_name'] = array('like',"%{$keywords}%");
    	}
    	
    	//上架
    	$is_on_sale = I('request.is_on_sale','1','trim');
    	if( is_numeric($is_on_sale) ){
    		$where['is_on_sale']=intval($is_on_sale);
    	}
    	//当前售价
    	$goods_price_start = I('request.goods_price_start','','trim');
    	$goods_price_end = I('request.goods_price_end','','trim');
    	$price_compare_str = '';
    	if( is_numeric($goods_price_start) ){
    		$price_compare_str.=" and shop_price >= {$goods_price_start} ";
    	}
    	if( is_numeric($goods_price_end) ){
    		$price_compare_str.=" and shop_price <= {$goods_price_start} ";
    	}

    	//库存数量
    	$goods_stock_start = I('request.goods_stock_start','','trim');
    	if( is_numeric($goods_stock_start) ){
    		$price_compare_str.=" and goods_number >= {$goods_stock_start} ";
    	}
    	$goods_stock_end = I('request.goods_stock_end','','trim');
    	if( is_numeric($goods_stock_end) ){
    		$price_compare_str.=" and goods_number <= {$goods_stock_end} ";
    	}
    	
    	$price_compare_str = ltrim(trim($price_compare_str),'and');
    	if( !empty($price_compare_str) ){
    		$where['_string'] = $price_compare_str;
    	}
    	
    	//类别id
    	$cat_id = I('request.cat_id',0,'intval');
    	if( !empty($cat_id) ){
    		$where['cat_id'] = $cat_id;
    	}
    	//品牌Id
    	$brand_id = I('request.brand_id',0,'intval');
    	if( !empty($brand_id) ){
    		$where['brand_id'] = $brand_id;
    	}
    	
    	$is_new = I('request.is_new',0,'intval');//是否新
    	if( !empty($is_new) ){
    		$where['is_new'] = $is_new;
    	}
    	$is_hot = I('request.is_hot',0,'intval');//是否热销
    	if( !empty($is_hot) ){
    		$where['is_hot'] = $is_hot;
    	}
    	$is_promote = I('request.is_promote',0,'intval');//是否特卖
    	if( !empty($is_promote) ){
    		$where['is_promote'] = $is_promote;
    	}
    	$current_price_type = I('request.current_price_type',0,'intval');//是否折扣商品
    	if( !empty($current_price_type) ){
    		$where['current_price_type'] = $current_price_type;
    	}
    	
    	$start_time = I('request.start_time','','trim');//创建时间 start
    	$end_time = I('request.end_time','','trim');//创建时间 end
    	if( !empty($start_time) && !empty($end_time)  ){
    		$where['add_time']=array('between',array( strtotime($start_time),strtotime($end_time) ) );
    	}else{
    		$_time = empty($start_time)?$end_time:$start_time;
    		if( !empty($_time) ){
    			$where['add_time'] = strtotime($_time);
    		}
    	}
    	
    	//排序
    	$_sort = I('request._sort',' DESC ','trim');
    	//排序字段
    	$_sort_column = I('request._sort_column',' goods_id ','trim');
    	$this->assign('_sort',$_sort);
    	$this->assign('_sort_column',$_sort_column);
    
    
    	$where['is_delete'] = 0;
    	$where['is_general'] = 1;//is_general=1的才显示
    	$stringwhere='';
    

    	$_listrows = I('request._listrows', 20, 'intval');
    	$stringwhere  = ltrim(trim($stringwhere),'and');
    	if(!empty($stringwhere)){
    		$where['_string']=$stringwhere;
    	}
    
    	$_where_order_field["where"] = $where;
    	$_where_order_field['order']=$_sort_column.' '.$_sort;
    	$_where_order_field['field']=" is_on_sale,goods_id,warn_number,cat_id,goods_img,goods_sn
    				,goods_name,brand_id,goods_number,sold,market_price,goods_item_id,goods_englishname
    			    ,cast(goods_point as decimal(9,1)) as goods_point,convert(goods_weight*1000,decimal) as goods_weight
    				,shop_price,goods_img,add_time,is_best,is_new,is_hot,is_real,is_promote,first_price,wait_sendgoods_stock
    				,(cast(g.goods_number as signed) - cast(g.wait_sendgoods_stock as signed)) as can_sale_goods_number";
    	$_where_order_field['listrows'] = $_listrows;
    	$_where_order_field["id"]="load_tb_div";
    	$_where_order_field['alias']="g";
    	$goods_list = $this->_getListsFromModel('goods',$_where_order_field);
    
		$goods_db = M('goods');
    	foreach($goods_list["lists"] as $key=>$value){			
			//,'is_general'=>0
			$attr_count = $goods_db->where(array('goods_item_id'=>$value['goods_item_id']))->count();
			if( empty($value['goods_item_id'])  ){
				$attr_count = 0;
			}
    		$goods_list["lists"][$key]["attrs_count"] =intval($attr_count);

			$btnStyle="";
			if($attr_count>1){
				$btnStyle="btn-success";
			}else{
				$btnStyle="btn-default";
			}
			$goods_list["lists"][$key]['btnStyle']=$btnStyle;

    	}
    	$this->assign('_datalist',$goods_list);
    
    	$this->display();
    }
    
    
    /* loadding attr items 加载属性商品数据 */
    function loaddingAttrGoodsList(){
    	//goods_item_id
    	$goods_item_id = I('request.goods_item_id',0,'intval');
    	
    	if( !empty($goods_item_id) ){
    		$_field=" is_on_sale,goods_id,warn_number,cat_id,goods_img,goods_sn
    				,goods_name,brand_id,goods_number,sold,market_price,goods_item_id
    			    ,cast(goods_point as decimal(9,1)) as goods_point,convert(goods_weight*1000,decimal) as goods_weight
    				,shop_price,goods_img,add_time,is_best,is_new,is_hot,is_real,first_price,wait_sendgoods_stock,retail_price,shop_price,vip_price
    				,(cast(g.goods_number as signed) - cast(g.wait_sendgoods_stock as signed)) as can_sale_goods_number,attribute_text,is_general";
    		 
    		$goods_items = M('goods')->alias('g')->field($_field)->where(array('goods_item_id'=>$goods_item_id,'is_delete'=>0))->order('is_general desc')->select();
    		// foreach ($goods_items as $key => $value) {
                
            //   $goods_items[$key]['wait_sendgoods_stock']=_get_goods_wait_sendgoods_stock($value['goods_id']);
            //    $goods_items[$key]['can_sale_goods_number']=_get_goods_cansale_count($value['goods_id']);
            // }

            $this->assign('goods_items',$goods_items);
    	}    	
    	
    	$this->display();
    }
    
    //修改商品
    public function edit(){

    	//商品编号
    	$goods_id = I('request.goods_id',0,'intval');
    
    	if(empty($goods_id)){
    		echo '参数错误-'.$goods_id;
    		exit;
    	}
    	
    	
    	$is_attr = I('request.is_attr',0,'intval');
    	if( $is_attr == 1 ){
    		
    		$goods = M('goods')->where(array('goods_id'=>$goods_id))->find();
    		//新版获取代发货库存和可售库存
    		$goods['wait_sendgoods_stock']=_get_goods_wait_sendgoods_stock($goods_id);
    		$goods['can_sales_num']=_get_goods_cansale_count($goods_id);
    		
    		
    		//查询商品
    		if ($goods['goods_weight'] > 0)
    		{
    			$goods['goods_weight_by_unit'] = doubleval( ($goods['goods_weight'] >= 1) ? $goods['goods_weight'] : ($goods['goods_weight'] / 0.001) );
    		}
    		$this->assign('weight_unit',  ($goods['goods_weight'] >= 1 ? '1' : '0.001'));
    		
    		$this->assign('goods',$goods);
    		$this->display('editAttrItems');
    		exit;
    	}
    
    	if(IS_POST){
    		$this->edit_post();
    		exit;
    	}

    	//关联记录
    	$link_goods_list = $this->get_linked_goods($goods_id);
    	$this->assign('link_goods_list',$link_goods_list);
    
    	//查询商品类别
    	$cat_list=M('category')->where(array('isshow'=>1))->order('sort_order')->select();
    	$goods_cats = list_to_tree($cat_list,'cat_id','parent_id','childs');
    	$this->assign('goods_cats',$goods_cats);
    
    	//查询商品品牌
    	$brand_list=M('brand')->where(array('isshow'=>1))->order('brand_name')->select();
    	$this->assign('brand_list',$brand_list);
    
    	//查询商品
    	$goods=M('goods')
			->field('goods_id,goods_name,goods_englishname,remark,minbuynumber,maxbuynumber,maxallbuy_count,sold,cat_id,brand_id,goods_number,
					wait_sendgoods_stock,warn_number,is_best,is_new,is_hot,keywords,goods_brief,seller_note,
					goods_sn,bar_code,is_on_sale,is_milk,is_red_wine,is_food,is_try,is_on_pre_sale,custom_clearance_price,distribution,
					taxrate,shelfnumber,first_goods_img,goods_desc,goods_weight,goods_item_id')
			->find($goods_id);
    	if ($goods['goods_weight'] > 0)
    	{
    		$goods['goods_weight_by_unit'] = ($goods['goods_weight'] >= 1) ? $goods['goods_weight'] : ($goods['goods_weight'] / 0.001);
    	}
    	$this->assign('weight_unit',  ($goods['goods_weight'] >= 1 ? '1' : '0.001'));
    
		//新版获取代发货库存和可售库存
    	$goods['wait_sendgoods_stock']=_get_goods_wait_sendgoods_stock($goods_id);
    	$goods['can_sales_num']=_get_goods_cansale_count($goods_id);

    	//商品首图
    	//正价
    	if( !empty($goods['first_goods_img']) ){
    		$first_img_info = M('attachment')->where(array('CONCAT("attas/",file_name)'=>$goods['first_goods_img']))->find();
    		$this->assign('first_img_info',$first_img_info);
    	}    	
    	//折扣
    	if( !empty($goods['discount_goods_img']) ){
    		$discount_img_info = M('attachment')->where(array('CONCAT("attas/",file_name)'=>$goods['discount_goods_img']))->find();
    		$this->assign('discount_img_info',$discount_img_info);
    	}
    	//特卖
    	if( !empty($goods['sale_goods_img']) ){
    		$sale_img_info = M('attachment')->where(array('CONCAT("attas/",file_name)'=>$goods['sale_goods_img']))->find();
    		$this->assign('sale_img_info',$sale_img_info);
    	}
    	
    	//查询商品对应图片列表
    	$goods_pics = M('goods_gallery')->alias('gg')
	    	->join(array(
	    			CTN('attachment').' as atta on CONCAT("attas/",atta.file_name) = gg.thumb_url '
	    	))
    	->field('gg.goods_id,atta.id,atta.file_name,gg.img_id as gallery_id')
    	->where(array('gg.goods_id'=>$goods_id))
    	->order('gg.img_sort')
    	->select();
    	$this->assign('goods_pics',$goods_pics);


		//查询商品对应价格策略
		if( !empty($goods['goods_item_id']) ){
			//得到该 goods_item_id 下的所有商品SKU记录
			$goodsList=M('goods')
				->field('goods_id,goods_sn,bar_code,goods_weight,shop_price,retail_price,vip_price,current_price_type,sale_price
					,first_goods_point,discount_goods_point,sale_goods_point,attribute_text,is_general')
				->where(array('goods_item_id'=>$goods['goods_item_id'],'is_delete'=>0))
				->order('is_general desc')->select();
			$this->assign('goodsList',$goodsList);
		}




//		$attribute_group_id_list = M('goods_attribute_extends_items')->where(array('goods_item_id'=>$goods_item_id,'is_delete'=>0))->group('attribute_group_id')->getField('attribute_group_id',true);
//		foreach ($attribute_group_id_list as $k=>$v){
//			$is_img=M('goods_attribute_group')->where(array('id'=>$v,'is_delete'=>0))->getField('is_image');
//			if($is_img==1){
//				$groupList=M('goods_attribute_extends_items')->where(array('attribute_group_id'=>$v,'is_delete'=>0))->select();
//			}
//		}


		//查找需要上传图片的groupID
		$is_img_group_id=M('goods_attribute_group')->where(array('is_image'=>1,'is_delete'=>0))->getField('id',true);
		if(!empty($is_img_group_id)){

            //把数组编程逗号隔开的字符串
            $is_img_group_id=implode(',', $is_img_group_id);


			$where['goods_item_id'] = $goods['goods_item_id'];
			$where['is_delete'] = 0;
			$where['attribute_group_id'] = array ('in',$is_img_group_id);
			//根据item_id和需要上传图片的group_id的in查询得到商品所有属性记录
			$groupList=M('goods_attribute_extends_items')->where($where)->select();


			//多属性图片记录表
			$images_model = M('goods_item_attrvalue_images');
			foreach ( $groupList as $k1=>$v1){
				//foreach循环得到属性文字分配到界面
				$v1['attribute_value'] = M('goods_attribute_value')->where(array('id'=>$v1['goods_attribute_value_id']))->getField('value');
				//去属性值上传图片记录表查找图片名称
				$image_name=$images_model->
				where(array('goods_item_id'=>$goods['goods_item_id'],'attribute_group_id'=>$v1['attribute_group_id'],
					'goods_attribute_value_id'=>$v1['goods_attribute_value_id']))->getField('image_name');
				//通过图片名称去附件表查找图片信息
				$v1['attrvalue_images_info'] = M('attachment')->where(array('file_name'=>$image_name))->find();
				$groupList[$k1]=$v1;
			}
			$this->assign('groupList',$groupList);
		}

		
		
    	$this->assign('page_title','编辑商品');
    	$this->assign('goods',$goods);

    	$this->display('add');
    	exit;
    }
    public function edit_post(){
    	
    	$goods_id = I('request.goods_id',0,'intval');
    	if( empty($goods_id) ){
    		$this->error('参数错误');
    		exit;
    	}
		
    	//重量单位
    	$weight_unit = doubleval($_POST['weight_unit']);
    	
    	//首先移除不需要修改的内容
    	unset($_POST['goods_number']);
    	unset($_POST['wait_sendgoods_stock']);
    	unset($_POST['can_sales_num']);
    	unset($_POST['goods_sn']);
    	unset($_POST['bar_code']);
    	unset($_POST['weight_unit']);    
    	unset($_POST['goods_id']);
    	
		//商品详细需要单独处理下
		$_POST['goods_desc' ]=str_replace("\\",'',$_POST['goods_desc']);  
    	//重量
    	$_POST['goods_weight'] = doubleval($_POST['goods_weight']*$weight_unit);
    	//是否上架
    	$is_on_sale = I('request.is_on_sale',0,'intval');
    	if( $is_on_sale == 0 ){
    		unset($_POST['start_time']);
    	}else{
    		$_POST['start_time'] = empty($_POST['start_time'])?time():local_strtotime($_POST['start_time']);
    	}
    	
    	//设置商品首图 
    	//正价首图
    	$first_goods_img = I('request.first_goods_img','','trim');

    	if(!empty($first_goods_img) ){
			// $first_img_info = M('attachment')->where(array('file_name'=>array('like','%'.$first_goods_img.'%')))->find();
            //          print_r($first_img_info);die;
			// if(!empty($first_img_info)){
			// 	$_POST['first_goods_img'] = 'attas/'.ltrim($first_goods_img[0],'//');
			// 	//更新图片字段临时存储值
			// 	$tmp_pic = 'attas/'.ltrim($first_goods_img[0],'//');//默认正价图片
			// }else{}

			$_POST['first_goods_img'] = ltrim($first_goods_img[0],'//');
			$tmp_pic = ltrim($first_goods_img[0],'//');//默认正价图片
			
    	}
    	//折扣价
    	$discount_goods_img = I('request.discount_goods_img','','trim');
    	if( !empty($discount_goods_img) ){
    		$_POST['discount_goods_img'] = 'attas/'.ltrim($discount_goods_img[0],'//');
    	}
    	//特卖价
    	$sale_goods_img = I('request.sale_goods_img','','trim');
    	if( !empty($sale_goods_img) ){
    		$_POST['sale_goods_img'] = 'attas/'.ltrim($sale_goods_img[0],'//');
    	}
    	

    	//$current_price_type 售价模式
    	$current_price_type = I('request.current_price_type',0,'intval');
    	if( $current_price_type == 3 ){
    		//当前特卖模式 就要设置is_promote =1
    		$_POST['is_promote'] = 1;
    		$tmp_pic = 'attas/'.ltrim($sale_goods_img[0],'//');
    	}elseif( $current_price_type == 2 ){
    		$tmp_pic = 'attas/'.ltrim($discount_goods_img[0],'//');
    	}
 
    	 
    	//先移除
    	unset($_POST['original_img']);
    	unset($_POST['goods_thumb']);
    	unset($_POST['goods_img']);
    	if( !empty($tmp_pic) ){
    		$_POST['original_img']=$tmp_pic;
    		$_POST['goods_thumb']=$tmp_pic;
    		$_POST['goods_img']=$tmp_pic;
    	}
    	
    	//修改商品播放图片 gallery_img
    	$pics = I('request.gallery_img_pic','','trim');
    	$gallery_id = I('request.gallery_id','','trim');
		$attachment_db = M('attachment');
    	$goods_gallery_db = M('goods_gallery');
    	if( !empty($pics) ){    		
    		//所有的gallery_img_ids
    		$gallery_img_ids = $goods_gallery_db->where(array('goods_id'=>$goods_id))->getField('img_id',true);
    		foreach($pics as $key=>$value){
    			$row = $attachment_db->where(array('id'=>intval($value)))->getField('file_name');
    			
    			$img_id = intval($gallery_id[$key]);//详情图片ID    		
    			$sort = $key;//详情图片排序    	
    			//查找key
    			if( !empty($img_id) ){
    				$img_id_key = array_search($img_id,$gallery_img_ids);
    				if( $img_id_key !== false ){
    					//移除
    					unset($gallery_img_ids[$img_id_key]);
    				}
    			}    	

				//判断文件是否存在
				$_row = '/attas/'.$row;
				if( !file_exists('.'.$_row) ){
					$_row = '/attas/orgimg'.$row;
				}		
				$_row = ltrim($_row,'//');
    		
    			if(!empty($img_id)){
    				$goods_gallery_db->where(array('img_id'=>$img_id))
    							->save(array(
    								'goods_id'=>$goods_id,
    								'img_url'=>$_row,
    								'thumb_url'=>$_row,
    								'img_original'=>$_row,
    								'img_sort'=>$sort,
    							));    			
    			}else{
    				$data=array(
    						'goods_id'=>$goods_id,
    						'img_url'=>$_row,
    						'thumb_url'=>$_row,
    						'img_original'=>$_row,
    						'img_sort'=>$sort,
    				);
    				$goods_gallery_db->add($data);
    			}
    		}
    		
    		//删除页面删除的
    		if( !empty($gallery_img_ids) ){
    			$goods_gallery_db->where(array('img_id'=>array('in',$gallery_img_ids)))->delete();
    		}    		
    	}else{
			//等于就删除掉所用的对应的记录
			$goods_gallery_db->where(array('goods_id'=>$goods_id))->delete();
		}
    	
    	//admin_log
    	$is_on_sale = I('request.is_on_sale',0,'intval');
    	if($is_on_sale==1){
    		$log_info='上架商品：'.I('request.goods_sn','','trim');
    	}else{
    		$log_info='下架商品：'.I('request.goods_sn','','trim');
    	}
    	$admin_log_data=array(
    			'log_time'=>gmtime(),
    			'user_id'=>$_SESSION['admin_id'],
    			'log_info'=>stripslashes($log_info),
    			'ip_address'=>real_ip(),
    	);
    	M('admin_log')->add($admin_log_data);

        //设置勾选项目
        $_POST['is_on_sale']=$is_on_sale;
        $_POST['is_milk']=empty($_POST['is_milk'])?0:$_POST['is_milk'];
        $_POST['is_red_wine']=empty($_POST['is_red_wine'])?0:$_POST['is_red_wine'];
        $_POST['is_food']=empty($_POST['is_food'])?0:$_POST['is_food'];
        $_POST['is_try']=empty($_POST['is_try'])?0:$_POST['is_try'];
        $_POST['is_on_pre_sale']=empty($_POST['is_on_pre_sale'])?0:$_POST['is_on_pre_sale'];
        $_POST['is_join_preferential']=empty($_POST['is_join_preferential'])?0:$_POST['is_join_preferential'];
        
        $_POST['is_best']=empty($_POST['is_best'])?0:$_POST['is_best'];
        $_POST['is_new']=empty($_POST['is_new'])?0:$_POST['is_new'];
        $_POST['is_hot']=empty($_POST['is_hot'])?0:$_POST['is_hot'];
        
    	// print_r($_POST);die;
    	
    	//保存修改的数据
    	$res = M('goods')->where(array('goods_id'=>$goods_id))->save($_POST);
    	
    	$goods_item_id = M('goods')->where(array('goods_id'=>$goods_id))->getField('goods_item_id');    	
    	if( !empty($goods_item_id) ){
    		//同时需要修改属性商品的上下架
    		unset($_POST['goods_englishname']);
            unset($_POST['goods_share_description']);
            unset($_POST['goods_share_title']);
            unset($_POST['first_goods_img']);
            unset($_POST['sale_goods_img']);
            unset($_POST['discount_goods_img']); 
            unset($_POST['goods_brief']); 
            unset($_POST['goods_desc']); 
            unset($_POST['goods_thumb']); 
            unset($_POST['original_img']);

            //记录一个应该保存的数据
            $goodsItemSaveData=$_POST; 
            $goodsItemList = M('goods')->field('goods_id,is_general')->where(array('goods_item_id'=>$goods_item_id))
				->order('is_general asc')
				->select();
            //重量单位 - 默认为 克
            $weight_unit = 0.001;
       
            foreach ($goodsItemList as $key => $value) {
                $goodsItemSaveData_item=$goodsItemSaveData;
                $sub_goods_id=$value['goods_id'];
                $is_general=$value['is_general'];
                //如果是主商品记录，则之前的记录不更新了，只更新价格信息
                if($is_general==1){
                   $goodsItemSaveData_item= array();
                }


                $goods_weight_v = doubleval($_POST['goods_weight'.$sub_goods_id]*$weight_unit);
                $goodsItemSaveData_item['goods_weight']= $goods_weight_v;
                $goodsItemSaveData_item['retail_price']= doubleval($_POST['retail_price'.$sub_goods_id]);
                $goodsItemSaveData_item['shop_price']= doubleval($_POST['shop_price'.$sub_goods_id]);
                $goodsItemSaveData_item['vip_price']= doubleval($_POST['vip_price'.$sub_goods_id]);
                $goodsItemSaveData_item['first_goods_point']= doubleval($_POST['first_goods_point'.$sub_goods_id]);
                $goodsItemSaveData_item['discount_goods_point']= doubleval($_POST['discount_goods_point'.$sub_goods_id]);
                $goodsItemSaveData_item['sale_goods_point']= doubleval($_POST['sale_goods_point'.$sub_goods_id]);
                

                //更新商品记录
                M('goods')->where( array('goods_id'=>$sub_goods_id) )->save($goodsItemSaveData_item);
				// echo M('goods')->getLastSql();die;
            }

            //如果是多属性，则设置多属性商品里价格最小的为主商品价格
            if(count($goodsItemList)>1)
            {
               $this-> setGeneralGoodsPrice($goods_item_id);
            }
    	}


		//多属性图片保存逻辑
		//获取需要上传多属性图片的记录
		$attribute_extends_items_id_list = I('request.attribute_extends_items_id','','trim');
		//多属性图片记录表
		$images_model = M('goods_item_attrvalue_images');
		foreach ( $attribute_extends_items_id_list as $k=>$v){
			//查找属性组编号ID、属性值编号ID
			$attribute_extends_items = M('goods_attribute_extends_items')->field('attribute_group_id,goods_attribute_value_id')->where(array('id'=>$v))->find();
			$g_group_img= I($v);
			if( !empty($g_group_img) ){
				//查找多属性图片记录表是否有该goods_item_id、属性组编号ID、属性值编号ID的记录
				$images_entity=$images_model->
				where(array('goods_item_id'=>$goods_item_id,'attribute_group_id'=>$attribute_extends_items['attribute_group_id'],
					'goods_attribute_value_id'=>$attribute_extends_items['goods_attribute_value_id']))->find();
				//如果记录为空则新增属性值图片记录
				if(empty($images_entity)){
					$img_data['goods_item_id']=$goods_item_id;
					$img_data['attribute_group_id']=$attribute_extends_items['attribute_group_id'];
					$img_data['goods_attribute_value_id']=$attribute_extends_items['goods_attribute_value_id'];
					$img_data['image_name'] = str_replace('/attas//','',$g_group_img[0]);
					$images_model->add($img_data);
				}else{
					//如果有记录则只更新图片字段
					$update_img_data['image_name'] = str_replace('/attas//','',$g_group_img[0]);
					$images_model->
					where(array('goods_item_id'=>$goods_item_id,'attribute_group_id'=>$attribute_extends_items['attribute_group_id'],
						'goods_attribute_value_id'=>$attribute_extends_items['goods_attribute_value_id']))->save($update_img_data);
				}
			}
		}



//     	if( $res ){
			//释放内存
			$goodsItemSaveData_item=null;
			$goodsItemSaveData=null;

			//清除缓存
    		clear_sys_cache();
    	
    		$this->success('操作成功!');
//     	}else{
//     		$this->error('操作失败，或未修改任何内容!');
//     	}    	
    	
    	exit;
    }
    
    
    /* 修改商品属性项 */
    public function editAttrItems(){
    	$goods_id = I('request.goods_id',0,'intval');
    	if( empty($goods_id) ){
    		$this->error('参数错误');exit;
    	}
    	
    	$goods_item_id = M('goods')->where(array('goods_id'=>$goods_id))->getField('goods_item_id');   
    	//获取is_general=1的商品id;
    	$_parent_goods_id = M('goods')->where(array('goods_item_id'=>$goods_item_id,'is_general'=>1))->getField('goods_id');
    	
    	$goodsItemSaveData_item=array();

    	//重量单位
    	$weight_unit = 0.001;
        $goods_weight_v = doubleval($_POST['goods_weight'.$goods_id]*$weight_unit);
        $goodsItemSaveData_item['goods_weight']= $goods_weight_v;
 

        $goodsItemSaveData_item['retail_price']= doubleval($_POST['retail_price'.$goods_id]);
        $goodsItemSaveData_item['shop_price']= doubleval($_POST['shop_price'.$goods_id]);
        $goodsItemSaveData_item['vip_price']= doubleval($_POST['vip_price'.$goods_id]);
        $goodsItemSaveData_item['first_goods_point']= doubleval($_POST['first_goods_point'.$goods_id]);
        $goodsItemSaveData_item['discount_goods_point']= doubleval($_POST['discount_goods_point'.$goods_id]);
        $goodsItemSaveData_item['sale_goods_point']= doubleval($_POST['sale_goods_point'.$goods_id]);
    
    	M('goods')->where(array('goods_id'=>$goods_id))->save($goodsItemSaveData_item);


        $goodsItemList_count=M('goods')->where(array('goods_item_id'=>$goods_item_id,'is_delete'=>0,'is_general'=>0))->count();
        //如果是多属性，则设置多属性商品里价格最小的为主商品价格
        if($goodsItemList_count>1)
        {
           $this-> setGeneralGoodsPrice($goods_item_id);
        }
    	
    	//清除缓存
    	clear_sys_cache();
    	
    	$this->success("操作成功<script>
    					 var parent = art.dialog.opener;		            	 
		            	 setTimeout(function(){
    						 parent.loaddingAttrItems({$_parent_goods_id},{$goods_item_id},1);
		            		 art.dialog.close();
		            	 },1200);		       
    			</script>");exit;    	
    }
    
	/* 加载多属性记录2 */
	public function loaddingAttrsList(){
		$goods_item_id = I('request.goods_item_id',0,'intval');
		if( !empty($goods_item_id) ){
			//得到该 goods_item_id 下的所有商品SKU记录
			$goodsList=M('goods')
				->field('goods_id,goods_sn,bar_code,goods_weight,shop_price,retail_price,vip_price,current_price_type,sale_price
					,first_goods_point,discount_goods_point,sale_goods_point,attribute_text,is_general')
				->where(array('goods_item_id'=>$goods_item_id,'is_delete'=>0))
				->order('is_general desc')->select();
			$this->assign('goodsList',$goodsList);
		}
		

		$this->display();
	}


    /* 加载多属性商品记录1 */
    public function loaddingAttrsList_Back(){
    	
    	$goods_item_id = I('request.goods_item_id',0,'intval');
    	if( empty($goods_item_id) ){
    		echo '<script>$("#create_table_div").empty().html("<span style=\'font-size:14px;\'>无多属性数据</span>");</script>';
    		exit;
    	}
    	
    	//查找处属性组
    	$goods_attribute_extends_items_Entity=M("goods_attribute_extends_items")
    		->where(array("goods_item_id"=>$goods_item_id,'is_delete'=>0))->order(' attribute_group_id desc ')->select();
    	// print_r($goods_attribute_extends_items_Entity);die;
    	$this->assign("goods_attribute_extends_items_Entity",$goods_attribute_extends_items_Entity);
    	
    	$attribute_group_array=array();//标题组数
    	$attribute_array=array();//盛放每组选中的对象
    	$attribute_columns_array=array(); //指定列，用来合并哪些列
    	
    	$current_row_index=0;
    	$goods_attribute_group_db = M('goods_attribute_group');
    	$goods_attribute_value_db = M('goods_attribute_value');
    	//{ "attribute_group_name": attribute_group_name, "group_id": group_id }
    	//{ "attribute_value": attribute_value, "attribute_value_id": attribute_value_id, "attribute_group_id": attribute_group_id, "attribute_group_name": attribute_group_name }
    	$cur_iterator_group_id = 0; //当前属性组
    	$cur_group_arry=array();
    	foreach ($goods_attribute_extends_items_Entity as $k =>$v){
    		$goods_attribute_value = $goods_attribute_value_db->field(' value as attribute_value,id as attribute_value_id ')->find(intval($v['goods_attribute_value_id']));
    		$goods_attribute_group = $goods_attribute_group_db->field(' name as attribute_group_name,id as group_id ')->find(intval($v['attribute_group_id']));
    		if( !isset($attribute_group_array[intval($v['attribute_group_id'])]) ){
    			//没有设置过组的，进来
    			$attribute_group_array[intval($v['attribute_group_id'])] = $goods_attribute_group;
    		}    		
    		
    		$cur_iterator_group_id = intval($v['attribute_group_id']);    		
    		$cur_group_arry[$cur_iterator_group_id][]=array(
    			'attribute_value'=>$goods_attribute_value['attribute_value'],
    			'attribute_value_id'=>$goods_attribute_value['attribute_value_id'],
    			'attribute_group_id'=>$goods_attribute_group['group_id'],
    			'attribute_group_name'=>$goods_attribute_group['attribute_group_name'],
    		);	
    		
    		$attribute_columns_array[]=$k;
    		$current_row_index++;
    	}    	
    	//设置数据数组
    	$attribute_array = array_values($cur_group_arry);
    	
    	$this->assign( 'attribute_group_array', json_encode(array_values($attribute_group_array)) );
    	$this->assign( 'attribute_array',json_encode($attribute_array) );
    	$this->assign( 'attribute_columns_array',json_encode($attribute_columns_array) );
    	$this->assign( 'current_row_index',$current_row_index );
    	
    	//得到属性商品记录，由于商品表字段比较多，必须通过 field设置只查询当前用到的字段
    	$goods_attribute_extends_skuList=M("goods")
    		->field('properties,goods_sn,goods_id,if(goods_name <> "" and goods_name is not null,goods_name,goods_englishname) as goods_name
    				,convert(goods_weight*1000,decimal) as goods_weight,bar_code,goods_number')
    		->where(array("goods_item_id"=>$goods_item_id,'is_general'=>0,'is_delete'=>0))->select();
    	foreach($goods_attribute_extends_skuList as $key=>$value){
    		$goods_attribute_extends_skuList[$key]["properties"]=implode("_",explode(",",$value["properties"]));
    		
    		if ($value['goods_weight'] > 0)
    		{
    			$goods_attribute_extends_skuList[$key]['goods_weight'] = ($value['goods_weight'] >= 1) ? $value['goods_weight'] : ($value['goods_weight'] / 0.001);
    		}
    	}
    	$this->assign("goods_attribute_extends_sku",json_encode($goods_attribute_extends_skuList));
    	
    	$this->display();    	
    }
    
    /* get_goods_list 查找商品 */
    public function get_goods_list(){
    	
    	$cat_id = I('request.cat_id',0,'intval');//分类id
    	$brand_id = I('request.brand_id',0,'intval');//品牌id
    	$keyword = I('request.keyword','','trim');//搜索关键词
    	$exclude = I('request.exclude','','trim');
    	
    	$where['is_general'] = 1;
    	$where['is_delete'] = 0;
    	
    	if(!empty($cat_id)){
    		$where['cat_id']=$cat_id;
    	}
    	if(!empty($brand_id)){
    		$where['brand_id']=$brand_id;
    	}
    	if(!empty($keyword)){
    		$where['goods_name|goods_sn']=array('like',"%{$keyword}%");
    	}
    	if(!empty($exclude)){
    		if(!is_array($exclude)){
    			$exclude = explode(',', $exclude);
    		}
    		$where['goods_id']=array('not in',$exclude);
    	}
    	
    	$goods_list = M('goods')->field('goods_id, goods_name, shop_price,goods_englishname')->where($where)->select();
    	$opt = array();
    	
    	foreach ($goods_list AS $key => $val)
    	{
    		$opt[] = array('value' => $val['goods_id'],
    				'text' => !empty($val['goods_name'])?$val['goods_name']:$val['goods_englishname'],
    				'data' => $val['shop_price']);
    	}
    	
    	$res = array('error' => 0, 'message' => '', 'content' => $opt);
    	echo json_encode($res);
    	exit;
    }
    
    /* 添加商品关联 */
    public function add_link_goods(){
    	    	
    	$linked_goods_ids = I('request.add_ids','','trim');//参数1   需要关联的商品
    	$linked_goods = I('request.other_args','','trim');//参数2  包含当前编辑的商品id及是否单向关联标记
    	
    	$goods_id       = intval($linked_goods[0]);
    	$is_double      = intval($linked_goods[1]);//页面返回的是否双向关联标记值 1是 0不是
    	
    	$link_goods_db = M('link_goods');//数据连接
    	
    	//查询是否存在，存在就显示
    	$count = $link_goods_db->where(array('goods_id'=>$goods_id,'link_goods_id'=>array('in',$linked_goods_ids)))->count();
    	if( $count < 1 ){
    		foreach ($linked_goods_ids AS $val)
    		{
    			if ($is_double)
    			{
    				/* 双向关联 */
    				$link_goods_data=array(
    						'goods_id'=>$val,
    						'link_goods_id'=>$goods_id,
    						'is_double'=>$is_double,
    						'admin_id'=>$_SESSION['admin_id'],
    				);
    				 
    				$link_goods_db->add($link_goods_data);
    			}
    			 
    			$link_goods_data=array(
    					'goods_id'=>$goods_id,
    					'link_goods_id'=>$val,
    					'is_double'=>$is_double,
    					'admin_id'=>$_SESSION['admin_id'],
    			);
    			$link_goods_db->add($link_goods_data);
    		
    		}
    	}    	
    	
    	$linked_goods = $this->get_linked_goods($goods_id);
    	$options      = array();
    	
    	foreach ($linked_goods AS $val)
    	{
    		$options[] = array('value'  => $val['goods_id'],
    				'text'      => !empty($val['goods_name'])?$val['goods_name']:$val['goods_englishname'],
    				'data'      => '');
    	}
    	
    	$res = array('error' => 0, 'message' => '', 'content' => $options);
    	echo json_encode($res);
    	exit;    	
    }
    
    /* 删除商品关联 */
    public function drop_link_goods(){
    	
    	$drop_goods_ids = I('request.drop_ids','','trim');//参数1   需要关联的商品
    	$linked_goods = I('request.other_args','','trim');//参数2  包含当前编辑的商品id及是否单向关联标记
    	 
    	$goods_id       = intval($linked_goods[0]);
    	$is_double      = intval($linked_goods[1]);//页面返回的是否双向关联标记值 1是 0不是
    	
    	$linked_goods_db = M('link_goods');//关联商品
    	//组装条件
    	$double_where = array('link_goods_id'=>$goods_id,'goods_id'=>array('in',$drop_goods_ids));
    	if ($goods_id == 0)
    	{
    		$double_where['admin_id'] = $_SESSION['admin_id'];
    	}
    	
    	if ($is_double)
    	{
    		$linked_goods_db->where($double_where)->delete();//删除
    	}
    	else
    	{
    		$linked_goods_db->where($double_where)->setField('is_double',0);
    	}
    	//组装删除
    	$delete_where = array('goods_id'=>$goods_id,'link_goods_id'=>array('in',$drop_goods_ids));
    	if ($goods_id == 0)
    	{
    		$delete_where['admin_id'] = $_SESSION['admin_id'];
    	}
    	M('link_goods')->where($delete_where)->delete();
    	
    	$linked_goods = $this->get_linked_goods($goods_id);
    	$options      = array();
    	
    	foreach ($linked_goods AS $val)
    	{
    		$options[] = array(
    				'value' => $val['goods_id'],
    				'text'  => !empty($val['goods_name'])?$val['goods_name']:$val['goods_englishname'],
    				'data'  => '');
    	}
    	
    	$res = array('error' => 0, 'message' => '', 'content' => $options);
    	echo json_encode($res);
    	exit;    	 
    }
    
    /**
     * 获得指定商品的关联商品
     *
     * @access  public
     * @param   integer     $goods_id
     * @return  array
     */
    function get_linked_goods($goods_id)
    {	
	    $where = array('lg.goods_id'=>$goods_id);
	    if( empty($goods_id) ){
	    	$where['lg.admin_id']=$_SESSION['admin_id'];
	    }
	    $row = M('link_goods')
	    		->alias('lg')
	    		->field('lg.link_goods_id AS goods_id, g.goods_name, lg.is_double, g.goods_englishname')
	    		->join(' ki_goods as g on lg.link_goods_id = g.goods_id ')
	    		->where($where)
	    		->select();
	    foreach ($row AS $key => $val)
	    {
	        $linked_type = $val['is_double'] == 0 ? '单向关联' : '双向关联';
	
	        $row[$key]['goods_name'] = !empty($val['goods_name'])?$val['goods_name']:$val['goods_englishname'] . " -- [$linked_type]";
	
	        unset($row[$key]['is_double']);
	    }
	
	    return $row;
    }
     
    //设置主商品记录的价格和重量
    function setGeneralGoodsPrice($goods_item_id){
        if(empty($goods_item_id)){
             return;
        }
        //得到多属性里价格最小的金额
        $minGoodsEntity = M('goods')->field(' min(shop_price) as shop_price,min(retail_price) as retail_price,min(vip_price) as vip_price 
            ,min(goods_weight) as goods_weight')
        ->where(array('goods_item_id'=>$goods_item_id,'is_delete'=>0,'is_general'=>0,'shop_price'=>array('neq',0)))
        ->find(); 
        //更新到主商品记录里
        $saveData=array();
        $shop_price=$minGoodsEntity['shop_price'];
        $retail_price=$minGoodsEntity['retail_price'];
        $vip_price=$minGoodsEntity['vip_price'];
        $goods_weight=$minGoodsEntity['goods_weight'];

        if(!empty($shop_price) && $shop_price>0)
        {
            $saveData['shop_price']=$shop_price;
        }

        if(!empty($retail_price) && $retail_price>0)
        {
            $saveData['retail_price']=$retail_price;
        }

        if(!empty($vip_price) && $vip_price>0)
        {
            $saveData['vip_price']=$vip_price;
        }

        if(!empty($goods_weight) && $goods_weight>0)
        {
            $saveData['goods_weight']=$goods_weight;
        }
 
        if($saveData){
           M('goods')->where( array('goods_item_id'=>$goods_item_id,'is_general'=>1) )->save($saveData);    
        }
        
    }
    
    
    
}



